﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Comdiv.QWeb.Utils {
	public static class ComplexStringHelper {
		private const string Regexmask = @"(^|\|){0}(:[^\|]+)?(\||$)";

		public static string Set(string target, string name, string value = null) {
			if (value.noContent() && IsComplex(name)) {
				return Set(target, Parse(name));
			}
			if (string.IsNullOrWhiteSpace(name)) return target;
			var val = string.IsNullOrWhiteSpace(value) ? name : string.Format("{0}:{1}", name, value);
			if (string.IsNullOrWhiteSpace(target)) return val;
			var regex = new Regex(string.Format(Regexmask, name));
			var result = target;
			if (regex.IsMatch(target)) {
				result = regex.Replace(target, "|" + val + "|");
			}
			else {
				result += "|" + val;
			}
			return Cleanup(result);
		}

		private static string Cleanup(string result) {
			result = result.Replace("||", "|");
			if (result.StartsWith("|")) result = result.Substring(1);
			if (result.EndsWith("|")) result = result.Substring(0, result.Length - 1);
			return result;
		}

		public static string Set(string target, IEnumerable<KeyValuePair<string, string>> data) {
			return data.Aggregate(target, (current, p) => Set(current, p.Key, p.Value));
		}

		public static string Remove(string target, string nameorvalue) {
			if (IsComplex(nameorvalue)) return Remove(target, Parse(nameorvalue));
			if (string.IsNullOrWhiteSpace(target)) return string.Empty;
			var result = Regex.Replace(target, string.Format(Regexmask, nameorvalue), "$1");
			return Cleanup(result);
		}

		public static string Remove(string target, IEnumerable<KeyValuePair<string, string>> data) {
			return data.Aggregate(target, (current, p) => Remove(current, p.Key));
		}

		private static bool IsComplex(string str) {
			if (string.IsNullOrWhiteSpace(str)) return false;
			return -1 != str.IndexOfAny(new[] {'|', ':'});
		}

		public static IDictionary<string, string> Parse(string str, char partdelimiter = '|', char valuedelimiter = ':') {
			var result = new Dictionary<string, string>();
			if (!string.IsNullOrWhiteSpace(str)) {
				var items = str.split(false, true, partdelimiter);
				foreach (var item in items) {
					var pair = item.split(false, true, valuedelimiter);
					var name = pair[0];
					var val = "";
					if (pair.Count > 1) {
						val = pair[1];
					}
					result[name] = val;
				}
			}
			return result;
		}
	}
}